package com.xbk.seckill.application.event;

import com.alibaba.cola.dto.Response;
import com.alibaba.cola.event.EventHandler;
import com.alibaba.cola.event.EventHandlerI;
import com.alibaba.fastjson.JSON;
import com.xbk.seckill.application.cache.SeckillGoodsCacheService;
import com.xbk.seckill.application.cache.SeckillGoodsListCacheService;
import com.xbk.seckill.goods.domain.event.SeckillGoodsEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;

/**
 * 商品事件处理器
 *
 * @author xiexu
 * @date 2025/2/5 15:18
 */
@Slf4j
@EventHandler
@ConditionalOnProperty(name = "message.mq.type", havingValue = "cola")
public class SeckillGoodsColaEventHandler implements EventHandlerI<Response, SeckillGoodsEvent> {

    @Autowired
    private SeckillGoodsCacheService seckillGoodsCacheService;

    @Autowired
    private SeckillGoodsListCacheService seckillGoodsListCacheService;

    @Override
    public Response execute(SeckillGoodsEvent seckillGoodsEvent) {
        if (seckillGoodsEvent.getId() == null) {
            log.info("cola|goodsEvent|接收秒杀品事件参数错误");
            return Response.buildSuccess();
        }
        log.info("cola|goodsEvent|接收秒杀品事件|{}", JSON.toJSON(seckillGoodsEvent));
        // 更新商品详情缓存
        seckillGoodsCacheService.tryUpdateSeckillGoodsCacheByLock(seckillGoodsEvent.getId(), false);
        // 更新商品列表缓存
        seckillGoodsListCacheService.tryUpdateSeckillGoodsCacheByLock(seckillGoodsEvent.getActivityId(), false);
        return Response.buildSuccess();
    }

}
